#ifndef _VISTA_THREAD_POOL_
#include "CVistaThreadPool.hpp"
#endif

#ifndef _GVLOCK_
#include "CLock.hpp"
#endif

/*--
     A timer class to scheule a call back as a timer job. It is using a dedicated 
     thread pool to perform the job
--*/
class CTimer  
{
private:
    //Keep an inside dedicated thread pool for schedule timer job
    static CVistaThreadPool s_pool;   
    DWORD m_Interval;
    volatile BOOL m_HasStarted;
    PTP_TIMER m_pTimer;
    CLock m_Lock;
            
public:
template<class TContext>
    CTimer(
        CWorkCallBack<TContext> *callBack, //Call back function
        DWORD millSecondsInterVal, //The interval of the timer job, 0 means one time timer job
        DWORD millSecondDelayStart=0): //Set the next start time
            m_Interval(millSecondsInterVal),
            m_HasStarted(FALSE)
    {
        m_pTimer=CreateThreadpoolTimer(&(CWorkCallBack<TContext>::TimerCallBack),callBack,&s_pool.m_TPENV);
    }

   void SetInterval(DWORD dwMilliSeconds)
   {
       m_Interval = dwMilliSeconds;      
       Start();

   }

   BOOL HasStarted()
   {
       return m_HasStarted;
   }
   
   void Start()
   {  
       m_Lock.Enter();

       if (!m_HasStarted)
       {
           FILETIME fileTime; 
           fileTime.dwHighDateTime=0xFFFFFFFF;
           fileTime.dwLowDateTime=0xFFFFFFFF;
           SetThreadpoolTimer(m_pTimer, &fileTime, m_Interval, 0);
           m_HasStarted=TRUE;   
       }

       m_Lock.Leave();
   }

   void Stop()
   {
       m_Lock.Enter();

       if (m_HasStarted)
       {
            SetThreadpoolTimer(m_pTimer, NULL, m_Interval, 0);
            m_HasStarted=FALSE;       
       }

       m_Lock.Leave();
   }
};

CVistaThreadPool CTimer::s_pool(4,8);